package com.bjsxt.lock2;

/**
 * 多个读操作可以同时进行，但读写、写写操作互斥
 */
public class TestReadWriteLock {

    public static void main(String[] args) {

        Operation operation = new Operation();

        Runnable readRunnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    operation.read();
                }
            }
        };
        //创建5个读线程并启动
        for (int i = 0; i < 5; i++) {

            new Thread(readRunnable, "读线程" + i).start();
        }

        Runnable writeRunnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    operation.write();
                }
            }
        };
        //创建5个写线程并启动
        for (int i = 0; i < 5; i++) {
            new Thread(writeRunnable, "写线程" + i).start();
        }
    }
}


class Operation {

    public void read() {
        System.out.println(Thread.currentThread().getName() + "开始读数据...");
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "读数据完毕...");
    }

    public void write() {
        System.out.println(Thread.currentThread().getName() + "开始写数据...");
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "写数据完毕...");
    }
}